<?php
/**
 * 接口请求公共处理
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2020/11/12
 * Time: 3:58 PM
 */
namespace Util\DaDa;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;

class Common
{

    // 授权KEY
    private $appKey = '';

    // 授权密钥
    private $appSecret = '';

    // 店铺编号
    private $sourceId = 0;

    public function __construct($appKey, $appSecret, $sourceId)
    {
        $this->appKey = $appKey;
        $this->appSecret = $appSecret;
        $this->sourceId  = $sourceId;
    }

    /**
     * 官网文档地址: http://newopen.imdada.cn/#/quickStart/develop/mustRead?_k=iuc6mw
     * 公共请求参数
     */
    public function CommonRequestParams()
    {
        return [
            'app_key'   => $this->appKey,
            'timestamp' => time(),
            'format'    => 'json',
            'v'         => '1.0',
            'source_id' => $this->sourceId,
        ];
    }

    /**
     * 官方文档地址: http://newopen.imdada.cn/#/quickStart/develop/safety?_k=6bwyag
     * 生成签名
     */
    public function getSignature($parm)
    {
        if(ksort($parm)){
            $stringA = '';
            //拼接成字符串stringA
            foreach($parm as $key => $value){
                if($value == 0 || !empty($value)){
                    $stringA .=$key.$value;
                }
            }
        }else{
            echo "对参数排序出错";
            exit();
        }

        //拼接后的字符串首尾加上app_secret秘钥
        $stringSignTemp = $this->appSecret.$stringA.$this->appSecret;

        //签名字符串进行MD5加密并且将签名生成的32位字符串转换为大写
        $signValue = strtoupper(md5($stringSignTemp));
        return $signValue;
    }

    /**
     * 公共处理返回结果
     */
    public function commonResponse($response)
    {
        if ($response['httpcode'] != 200) {
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }

        $responseData = json_decode($response['content'], true);
        if ($responseData['code']) {
            return ResultWrapper::fail($responseData['msg'], $responseData['code']);
        }
        return ResultWrapper::success($responseData['result']);
    }

}